package com.waikuai.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.waikuai.shop.entity.ProductCategory;
import com.waikuai.shop.mapper.ProductCategoryMapper;
import com.waikuai.shop.service.ProductCategoryService;
import com.waikuai.shop.vo.CategoryTreeVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商品分类服务实现类
 * @author waikuai
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ProductCategoryServiceImpl extends ServiceImpl<ProductCategoryMapper, ProductCategory>
        implements ProductCategoryService {

    private final ProductCategoryMapper productCategoryMapper;

    @Override
    public List<CategoryTreeVO> getCategoryTree() {
        try {
            // 获取所有启用的分类
            List<ProductCategory> allCategories = productCategoryMapper.selectEnabledCategories();
            return buildCategoryTree(allCategories);
        } catch (Exception e) {
            log.error("获取分类树失败: {}", e.getMessage(), e);
            throw new RuntimeException("获取分类树失败");
        }
    }

    @Override
    public List<ProductCategory> getTopLevelCategories() {
        try {
            return productCategoryMapper.selectTopLevelCategories();
        } catch (Exception e) {
            log.error("获取顶级分类列表失败: {}", e.getMessage(), e);
            throw new RuntimeException("获取顶级分类列表失���");
        }
    }

    @Override
    public List<ProductCategory> getCategoriesByParentId(Long parentId) {
        try {
            return productCategoryMapper.selectCategoriesByParentId(parentId);
        } catch (Exception e) {
            log.error("根据父分类ID获取子分类列表失败，父分类ID: {}, 错误: {}", parentId, e.getMessage(), e);
            throw new RuntimeException("获取子分类列表失败");
        }
    }

    @Override
    public List<ProductCategory> getEnabledCategories() {
        try {
            return productCategoryMapper.selectEnabledCategories();
        } catch (Exception e) {
            log.error("获取启用的分类列表失败: {}", e.getMessage(), e);
            throw new RuntimeException("获取启用分类列表失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createCategory(ProductCategory category) {
        try {
            // 设置默认值
            if (category.getParentId() == null) {
                category.setParentId(0L);
            }
            if (category.getLevel() == null) {
                category.setLevel(category.getParentId() == 0 ? 1 : 2);
            }
            if (category.getSortOrder() == null) {
                category.setSortOrder(0);
            }
            if (category.getStatus() == null) {
                category.setStatus(1);
            }

            int result = productCategoryMapper.insert(category);
            log.info("创建商品分类成功，分类ID: {}, 分类名称: {}", category.getId(), category.getCategoryName());
            return result > 0;
        } catch (Exception e) {
            log.error("创建商品分类失败: {}", e.getMessage(), e);
            throw new RuntimeException("创建商品分类失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateCategory(ProductCategory category) {
        try {
            int result = productCategoryMapper.updateById(category);
            if (result > 0) {
                log.info("更新商品分类成功，分类ID: {}, 分类名称: {}", category.getId(), category.getCategoryName());
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("更新商品分类失败: {}", e.getMessage(), e);
            throw new RuntimeException("更新商品分类失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteCategory(Long categoryId) {
        try {
            int result = productCategoryMapper.deleteById(categoryId);
            if (result > 0) {
                log.info("删除商品分类成功，分类ID: {}", categoryId);
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("删除商品分类失败: {}", e.getMessage(), e);
            throw new RuntimeException("删除商品分类失败");
        }
    }

    @Override
    public boolean checkCategoryNameExists(String categoryName, Long excludeId) {
        try {
            LambdaQueryWrapper<ProductCategory> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ProductCategory::getCategoryName, categoryName);
            if (excludeId != null) {
                queryWrapper.ne(ProductCategory::getId, excludeId);
            }
            return productCategoryMapper.selectCount(queryWrapper) > 0;
        } catch (Exception e) {
            log.error("检查分类名称是否存在失败: {}", e.getMessage(), e);
            return false;
        }
    }

    @Override
    public Integer countProductsByCategoryId(Long categoryId) {
        try {
            return productCategoryMapper.countProductsByCategoryId(categoryId);
        } catch (Exception e) {
            log.error("统计分类商品数量失败，分类ID: {}", categoryId, e);
            return 0;
        }
    }

    @Override
    public List<CategoryTreeVO> buildCategoryTree(List<ProductCategory> categories) {
        try {
            // 按父分类ID分组
            Map<Long, List<ProductCategory>> categoryMap = categories.stream()
                    .collect(Collectors.groupingBy(ProductCategory::getParentId));

            // 转换为VO对象
            Map<Long, CategoryTreeVO> voMap = categories.stream()
                    .collect(Collectors.toMap(ProductCategory::getId, category -> {
                        CategoryTreeVO vo = new CategoryTreeVO();
                        vo.setId(category.getId());
                        vo.setCategoryName(category.getCategoryName());
                        vo.setParentId(category.getParentId());
                        vo.setLevel(category.getLevel());
                        vo.setSortOrder(category.getSortOrder());
                        vo.setIcon(category.getIcon());
                        vo.setDescription(category.getDescription());
                        vo.setStatus(category.getStatus());
                        vo.setChildren(new ArrayList<>());
                        vo.setHasChildren(false);
                        return vo;
                    }));

            // 构建树结构
            List<CategoryTreeVO> treeList = new ArrayList<>();
            for (ProductCategory category : categories) {
                CategoryTreeVO vo = voMap.get(category.getId());
                if (category.getParentId() == 0) {
                    // 顶级分类
                    treeList.add(vo);
                } else {
                    // 子分类
                    CategoryTreeVO parent = voMap.get(category.getParentId());
                    if (parent != null) {
                        parent.getChildren().add(vo);
                        parent.setHasChildren(true);
                    }
                }
            }

            // 统计商品数量（这里简化处理，实际可能需要单独查询）
            for (CategoryTreeVO vo : voMap.values()) {
                Integer productCount = countProductsByCategoryId(vo.getId());
                vo.setProductCount(productCount);
            }

            return treeList;
        } catch (Exception e) {
            log.error("构建分类树失败: {}", e.getMessage(), e);
            return new ArrayList<>();
        }
    }
}